<?php
namespace App\Http\Controllers\Activity;

use App\Http\Controllers\Controller;
use App\Models\Activity;
use App\Models\ProxyMember;
use App\Models\Tools\Data;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class ActivityConsumeController extends Controller
{
    // 霸王餐审核核销
    public function index()
    {

        $all = $this->all;
        $act_id = $all['act_id'];

        try{
            DB::beginTransaction();

            // 查询活动信息
            $activity = DB::table('lottery_activity')->where('act_id','=',$act_id)->lockForUpdate()->first();
            $activity = json_decode(json_encode($activity), true);

            // 检查霸王餐活动是否到期：超过14天
            if(strtotime($activity['draw_time']) > Activity::overTime()){
                DB::rollBack();
                Log::error('霸王餐：核销时间过短',$activity);
                return $this->setReturnJson(-1,'核销失败，未到规定时间');
            }

            // 查询商家的霸王餐活动in_use数量
            $remaining = DB::table('lottery_remaining')->where('we_id','=',$activity['creator'])->lockForUpdate()->first();
            $remaining = json_decode(json_encode($remaining), true);
            if($remaining['in_use_times'] < 1){
                DB::rollBack();
                Log::emergency('核销数据错误：商家余量不足',['activity'=>$activity,'remaining'=>$remaining]);
                return $this->setReturnJson(-1,'核销数据错误：商家余量不足');
            }

            // 修改活动状态
            DB::table('lottery_activity')->where('act_id','=',$act_id)->update(['status'=>Data::DATA_DB_LOTTERY_ACTIVITY_STATUS_SUCCESS]);
            // 修改开奖状态
            DB::table('lottery_draw_detail')->where('act_id','=',$act_id)->update([
                'consumed'=>1,
                'consumed_at'=>date('Y-m-d H:i:s'),
                'consumed_by'=>$this->userInfo['id'],
            ]);
            // 修改用户存量
            DB::table('lottery_remaining')->where('we_id','=',$activity['creator'])->decrement('in_use_times');
            // 记录日志
            DB::table('lottery_remaining_log')->insert([
                'lr_id'=>$remaining['lr_id'],
                'action'=>4, // 核销
                'action_num'=>1,
                'rest_num'=>$remaining['remaining_times'],
                'in_use_num'=>$remaining['in_use_times'] - 1,
            ]);

            // 检查这个霸王餐的发单人是否有代理，以及推广时间，如果存在比例，那么需要给代理分成
            $apply_user = DB::table('lottery_users')->where('we_id','=',$activity['creator'])->first();
            $apply_user = json_decode(json_encode($apply_user), true);
            // 如果存在代理，计算返点:
            if(!is_null($apply_user['proxy'])){
                $proportion = ProxyMember::proportion($apply_user['proxy_at']);
                // 检查推荐时间，是否还有返利
                if($proportion > 0){
                    // 增加余额:
                    // 查询霸王餐活动现在的金额
                    $shop_type = DB::table('shop')->where('shop_id','=',$activity['shop_id'])->value('shop_type');
                    $lottery_price = DB::table('shop_type')->where('st_id','=',$shop_type)->value('lottery_price');
                    // 根据订单价格和返利比例，计算返利金额
                    $proxy_price = (int)floor($lottery_price * $proportion);
                    DB::table('proxy_users')
                        ->where('we_id','=',$apply_user['proxy'])
                        ->increment('wallet',$proxy_price);
                    DB::table('proxy_log')->insert([
                        'type'=>4,
                        'proxy_we_id'=>$apply_user['proxy'],
                        'consumer_we_id'=>$activity['creator'],
                        'payment'=>$lottery_price,
                        'proxy_price'=>$proxy_price,
                    ]);
                    // 给推荐人发送通知
                    ProxyMember::rebateNotice($apply_user['nickname'],$proxy_price,$apply_user['proxy']);
                }
            }
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            Log::error(ActivityConsumeController::class, ['msg' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]);
            return $this->setReturnJson(-1, '核销失败');
        }

        return $this->setReturnJson(0,'核销成功');

    }

}
